<?php
class Simpple_View_Default implements Simpple_View_Interface {
	private $vars = array();
	private $paths = array();
	private $prefix = 'phtml';
	
	/**
	 * 添加脚本路径
	 *
	 * @param string $path
	 */
	function addScriptPath($path) 
	{
		if (!$path) {
			return false;
		}
		$this->paths[] = $path;
	}
	
	/**
	 * 设置脚本路径的后缀
	 *
	 * @param string $prefix
	 */
	function setPrefix($prefix) 
	{
		$this->prefix = $prefix;
	}
	
	/**
	 * 分配变量
	 *
	 * @param string | array $key
	 * @param mixed $value
	 */
	function assign($key, $value) 
	{
		if (is_array($key)) {
			foreach($key as $k=>$v) {
				$this->vars[$k] = $v;
			}
		} else {
			$this->vars[$key] = $value;
		}
	}
	
	/**
	 * 显示页面内容
	 *
	 * @param string $path
	 */
	function display($path) 
	{
		if (!$path) {
			throw new Simpple_View_Exception("the path cann't be empty");
		}
		
		// 找到存在的脚本路径
		$fileName = '';
		for($i = count($this->paths) - 1; $i >= 0; $i--) {
			$p = $this->paths[$i];
			$p = $p.'/'.$path.'.'.$this->prefix;
			if (file_exists($p)) {
				$fileName = $p;
				break;
			}
		}
		if (!$fileName) {
			require_once 'Exception.php';
			throw new Simpple_View_Exception("cann't find the script({$path}.{$this->prefix}) from include paths(".implode(';', $this->paths).")");
		} else {
			include $fileName;
		}
	}
	
	/**
	 * 获取页面内容
	 *
	 * @param string $path
	 */
	function fetch($path) 
	{
		ob_start();
		include $path;
		$out = ob_get_clean();
		return $out;
	}
	
	/**
	 * 获取属性
	 *
	 * @param string $name
	 */
	function __get($name) 
	{
		return $this->vars[$name];
	}
	
	function __set($name, $value)
	{
		$this->vars[$name] = $value;
		return $this;
	}
}